<?php

class Controller_Main extends Core_Controller {
    const JS_TYPE_FUNCTIONALITY = 'Functionality/';
    const JS_TYPE_ELEMENT = 'Element/';

    protected $allowForHttp = array(
        '_index'
        , '_login'
        , '_jsElement'
        , '_jsFunctionality'
        , '_checkSession'
        , '_logout'
        , '_uc' 
    );
    protected $skipAuthentication = array(
        '_index'
        , '_login'
        , '_jsElement'
        , '_jsFunctionality'
        , '_checkSession'
        , '_logout'
        , '_uc'
        , '_test'
    );

    protected $inputValidationRules = array(
        'username' => array('type' => 'string'),
        'password' => array('type' => 'string'),
        'script' => array('type' => 'string')
    );


    public function _index() {
        //$this->view->setHeader('Content-type', 'text/plain');
        $this->view->setOutputType(Core_View::OUTPUT_TYPE_TEMPLATE);
        $this->view->setTemplate('uiLoader.tpl');

        $this->view->set('Name', 'Frontpage');
        $this->view->set(array(
            'jsUiList' => $this->getJavascriptElementList(),
            'jsList' => $this->getJavascriptFunctionalityList()
        ));
    }

    public function _uc() {
        $this->view->setOutputType(Core_View::OUTPUT_TYPE_TEMPLATE);
        $this->view->setTemplate('useCasePresentation.tpl');
        $this->view->baseUrl = trim(Core_Request::getBasePath(), '/');
    }

    public function _checkSession() {
        $this->view->setOutputType(Core_View::OUTPUT_TYPE_JSON);
        $this->view->set(array(
            'success' => $this->isSessionValid()
            , 'message' => 'Session ' . ($this->isSessionValid()
                    ? 'Ok' : 'invalid or not started')
        ));
    }

    protected function isSessionValid() {
        return isset($_SESSION['user']);
    }

    public function _login() {
        $this->view->setOutputType(Core_View::OUTPUT_TYPE_JSON);

        $user = Model_User::login(
                        $this->request->getPostData('username'),
                        $this->request->getPostData('password')
        );

        if ($user) {
            $_SESSION['user'] = serialize($user->serializeToArray());
            $this->view->set(array(
                'success' => true,
                'message' => 'Welcome '.$this->request->getPostData('username').'!',
                'userId' => $user->getId()
            ));
        } else {
            $this->returnErrorMessage('Pleace check your username and password');
        }
    }

    public function _logout() {
        $this->view->setOutputType(Core_View::OUTPUT_TYPE_JSON);

        session_unset();
        session_destroy();
        $this->view->set(array(
            'success' => true,
            'message' => 'Logged out',
            'redirUrl' =>  $this->request->getBaseUri()
        ));
    }

    public function _jsElement() {
        return $this->readScript(
                $this->request->getGetData('script'),
                self::JS_TYPE_ELEMENT
        );
    }

    public function _jsFunctionality() {
        return $this->readScript(
                $this->request->getGetData('script'),
                self::JS_TYPE_FUNCTIONALITY
        );
    }

    private function readScript($name, $type = self::JS_TYPE_FUNCTIONALITY) {
        $this->view->setOutputType(Core_View::OUTPUT_TYPE_DIRECT);
        $this->view->setHeader('Content-Type', 'text/javascript');

        if (!$name) {
            return $this->returnError('No script to be loaded');
        }

        if ($type == self::JS_TYPE_ELEMENT)
            $list = $this->getJavascriptElementList();
        else if ($type == self::JS_TYPE_FUNCTIONALITY)
            $list = $this->getJavascriptFunctionalityList();
        else
            return $this->returnError('Unknown script type: ' . $type);

        if (!in_array($name, $list)) {
            return $this->returnError("Unable to find requested file: '$name' from " . implode(',', $list));
        }

        $path = dirname(__FILE__) . '/../View/' . $type . $name;
        $content = file_get_contents($path);
        if (!$content) {
            return $this->returnError("Unable to read requested file: '$path'");
        } else {
            $this->view->setContent($content);
        }
    }

    private function getJavascriptElementList() {
        $fileList = scandir(dirname(__FILE__) . '/../View/Element');
        $jsList = array();
        foreach ($fileList as $aFile) {
            if (substr($aFile, -3) === '.js')
                $jsList[] = $aFile;
        }
        return $jsList;
    }

    private function getJavascriptFunctionalityList() {
        $fileList = scandir(dirname(__FILE__) . '/../View/Functionality');
        $jsList = array();
        foreach ($fileList as $aFile) {
            if (substr($aFile, -3) === '.js')
                $jsList[] = $aFile;
        }
        return $jsList;
    }
}
